package webx.actions;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.search.internal.ui.SearchPlugin;
import org.eclipse.search.ui.ISearchQuery;
import org.eclipse.search.ui.NewSearchUI;
import org.eclipse.search.ui.text.TextSearchQueryProvider;
import org.eclipse.search2.internal.ui.SearchMessages;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IStartup;

/**
 * 基于搜索项目和搜索关键字的WEB超链接搜索服务:
 * 解析网页超链接提交的字符串，获取参数"项目名称(projectName)" 和 搜索"字符串(searchString)"
 * 并启动eclipse的文本搜索功能进行字符串搜索,用以替代CTRL+H然后手动输入.
 * @author 王华荣 2014.7.4
 *
 */
@SuppressWarnings("restriction")
class FindRun extends Thread{
	// 项目名称
	static String projectName="";
	
	// 查找关键字
	static String searchString = "";
	
	// 内置服务器端口2014
	int port = 2014;
	@SuppressWarnings("resource")
	@Override
	public void run() {
		ServerSocket ser = null;
		try {
			ser = new ServerSocket(port);
		}catch (IOException e) {
			e.printStackTrace();
		}
		while(true){
			InputStream ins = null;
			Socket explor = null;
			try {
				System.out.println("等待读取url get:");
				explor = ser.accept();
				ins = explor.getInputStream();
				byte[] httprequest_data = new byte[ins.available()];
				ins.read(httprequest_data);
				String rstr = new String(httprequest_data,"UTF-8");
				String[] arr = rstr.split(" ");
				if(arr.length<=1){
					continue;
				}
				rstr = rstr.split(" ")[1];
				String param = rstr.substring(rstr.indexOf("?")+1);
				String[] params = param.split("&");
				for(int i=0;i<params.length;i++){
					String name = params[i].split("=")[0];
					String vale = params[i].split("=")[1];
                    vale = java.net.URLDecoder.decode(vale);
					if("projectName".equals(name)){
						projectName = vale;
					}
					if("searchString".equals(name)){
						searchString = vale;
					}
				}
				System.out.println("projectName:"+projectName);
				System.out.println("searchString:"+searchString);
				Display.getDefault().syncExec(new Runnable() {
			         public void run() {
			        	 
			        	try{
			        	   // searching... 
			        	   // 文本查找调度
			        	   TextSearchQueryProvider provider = TextSearchQueryProvider.getPreferred();
			        	   System.out.println("provider:"+provider);
							try
							{   // 文本查找器
								ISearchQuery query = createQuery(provider,projectName,searchString);
								
								if (query != null)
									// 搜索
									NewSearchUI.runQueryInBackground(query);
							}catch (OperationCanceledException _ex){
								_ex.printStackTrace();
							}
							catch (CoreException e){  
								e.printStackTrace();
								try{
									ErrorDialog.openError(getShell(), SearchMessages.RetrieverAction_error_title,
										SearchMessages.RetrieverAction_error_message, e.getStatus());
								}catch(Exception ex){
									ex.printStackTrace();
								}
							}
						    // searching end
			        	}catch(Exception ex){
			        		ex.printStackTrace();
			        	}
			        	
			          }
			         }
			      );
					
			} catch (IOException e) {
				e.printStackTrace();
			}
			finally{
				if(ins!=null){
					try {
						ins.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	private Shell getShell(){
		return SearchPlugin.getActiveWorkbenchShell();
	}
	
	protected ISearchQuery createQuery(TextSearchQueryProvider provider,String projectName, String searchString) throws CoreException
	{
		IWorkspace resource = ResourcesPlugin.getWorkspace();
		IProject project = resource.getRoot().getProject(projectName);
		
		if (project != null)
			return provider.createQuery(searchString, new IResource[] { project });
		else
			return provider.createQuery(searchString);
	}
}

public class Startup implements IStartup {
	public void earlyStartup() {
		Display.getDefault().syncExec(new Runnable() {
	         public void run() {
	        	 // start find server
	        	 // 启动搜索服务
	        	 new FindRun().start();
	         }
	      });
	   }
	
}